-- UIHeroUpgradeRank
-- Create by luohj Jan/19/2015
-- 英雄升阶界面

require "game/ui/form/training/UITrainingMain"
require "game/ui/form/hero/UIHeroSpeak"

-- UIHeroUpgradeRank继承自Layer
UIHeroUpgradeRank = class("UIHeroUpgradeRank", function()
    return cc.Layer:create();
end);

function UIHeroUpgradeRank.create(classId, openType)
    return UIHeroUpgradeRank.new(classId, openType);
end

-- 构造函数
function UIHeroUpgradeRank:ctor(classId, openType)
    -- 初始化
    self:setName("UIHeroUpgradeRank");

    local node = cc.CSLoader:createNode("layout/hero/HeroUpgradeRank.csb");
    self:addChild(node);
    self.node = node;
    local CT = node:getChildByName("CT");
    self.CT = CT;
    self.classId = classId;
    self.openType = openType;
    self.pet = PetM.getMyPet(classId);

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 初始化view
    self:initView();

    -- 绘制界面
    self:redraw();

    -- 适配
    self:resize();

    -- 注册点击事件
    self:registerTouchEvent();
end

function UIHeroUpgradeRank:initView()

end

-- 绘制界面
function UIHeroUpgradeRank:redraw()
    -- 绘制template
    -- 绘制标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");

    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(PetM.query(self.classId, "name"));

    TextStyleM.setSubheadStyle(subHeadLabel);

    if self.openType == "awake_carving" then
        -- 已完成地牢试炼，显示"英雄雕像""
        subHeadLabel:setString(getLocStr("hero_upgrade_awake_carving"));
    elseif self.openType == "awake_dungeon" then
        -- 未完成地牢试炼，显示"神庙の试炼"
        subHeadLabel:setString(getLocStr("awake_dungeon_title"));
    else
        subHeadLabel:setString(string.format(getLocStr("upgrade_titel"), self.pet:getRank() + 1));
    end

    -- 武器
    local weaponNode = findChildByName(self.node, "CT/weapon");
    -- 荣誉之证
    local medalNode = findChildByName(self.node, "CT/medal");
    -- 雕像
    local carvingNode = findChildByName(self.node, "CT/carving");

    -- 属性描述节点
    local propDescNode = findChildByName(self.node, "CT/prop_desc");
    propDescNode:removeAllChildren();

    -- 确定按钮
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    if self.openType == "upgrade" then
        -- 进阶界面。绘制武器和徽章
        weaponNode:setVisible(true);
        medalNode:setVisible(true);

        local weaponClassId = EquipM.getHeroEquip(self.pet, EQUIP_TYPE_WEAPON, 1);
        local medalClassId = EquipM.getHeroEquip(self.pet, EQUIP_TYPE_MEDAL, 1);
        local weaponBg = findChildByName(self.node, "CT/weapon/weapon_bg");
        local medalBg = findChildByName(self.node, "CT/medal/medal_bg");
        local weaponImage = findChildByName(self.node, "CT/weapon/icon");
        local medalImage = findChildByName(self.node, "CT/medal/icon");

        self.lastWeaponClassId = weaponClassId;
        self.lastMedalClassId = medalClassId;

        weaponNode.classId = nil;
        if weaponClassId then
            weaponNode.classId = weaponClassId;
            local iconIndex = ItemM.query(weaponClassId, "icon");
            weaponImage:loadTexture(getItemIconPath(iconIndex));
        else
            -- 获取需要合成的装备
            local needEquipClassId = PetM.getUpgradeRankEquip(self.pet, EQUIP_TYPE_WEAPON);
            if #needEquipClassId == 0 then
                error(string.format("获取不到宠物(%d)升阶所需的武器或徽章。", self.classId));
            else
                local iconIndex = ItemM.query(needEquipClassId[1], "icon");
                weaponImage:loadTexture(getItemIconPath(iconIndex));
                setGrayTransMode(weaponImage, true);
            end
        end

        -- 获取已经穿戴的徽章
        medalImage:loadTexture("images/ui/hero/medal.png");

        medalNode.classId = nil;
        if medalClassId then
            medalNode.classId = medalClassId;
            local iconIndex = ItemM.query(medalClassId, "icon");
            medalImage:loadTexture(getItemIconPath(iconIndex));
        else
            -- 获取需要合成的装备
            local needEquipClassId = PetM.getUpgradeRankEquip(self.pet, EQUIP_TYPE_MEDAL);
            if #needEquipClassId == 0 then
                error(string.format("获取不到宠物(%d)升阶所需的武器或徽章。", self.classId));
            else
                local iconIndex = ItemM.query(needEquipClassId[1], "icon");
                medalImage:loadTexture(getItemIconPath(iconIndex));
                -- 获取可穿戴提示控件 并隐藏
                setGrayTransMode(medalImage, true);
            end
        end

        -- 绘制进阶提升的属性
        local specialProp = FormulaM.invoke("PET_SPECIAL_PROP", self.classId, self.pet:getRank());
        local specialPropValue = specialProp[3] or 0;
        local props = {
                {"talent_skill_level", 1},
                {"attack", self.pet:getUpRankAddAttack(self.pet:getRank() + 1)},
                {"magic", self.pet:getUpRankAddMagic(self.pet:getRank() + 1)},
                {"max_hp", self.pet:getUpRankAddMaxHp(self.pet:getRank() + 1)},
                {"max_mp", self.pet:getUpRankAddMaxMp(self.pet:getRank() + 1)},
                {"special_prop", specialPropValue},
                {"career_type", self.pet:getUpRankAddCareerType(self.pet:getRank() + 1)},};

        local propDescText = "";
        local index = 1;
        for _, value in pairs(props) do
            if value[2] > 0 then
                local name = FieldsM.getFieldName(value[1]);
                if value[1] == "max_hp" then
                    name = FieldsM.getFieldName("hp");
                elseif value[1] == "max_mp" then
                    name = FieldsM.getFieldName("mp");
                elseif value[1] == "special_prop" then
                    name = FormulaM.invoke("PET_SPECIAL_PROP_DESC", specialProp);
                elseif value[1] == "talent_skill_level" then
                    name = getLocStr("talent_skill_level");
                elseif value[1] == "career_type" then
                    name = string.format(getLocStr("open_career_type"), getNameByDep(value[2]));
                end

                local desc;
                if value[1] == "career_type" then
                    desc = name;
                else
                    desc = name .. " + " .. value[2];
                end

                index = index + 1;

                local textStyle = { ["fontSize"] = TextStyleM.TEXT_SIZE_SMALL, ["color"] = TextStyleM.TEXT_COLOR_BLUE };

                -- 显示功能描述
                local textLabel = ccui.Text:create();
                textLabel:setPositionY(propDescNode:getPositionY() - 34 * (index - 1));
                TextStyleM.setTextStyle(textLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
                textLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
                textLabel:setString(desc);

                propDescNode:addChild(textLabel);
            end
        end

        -- "前往训练室"
        btnOk:setTitleText(getLocStr("go_training"));

        if weaponNode.classId and medalNode.classId then
            btnOk:setBright(true);
            btnOk:setTouchEnabled(true);
        else
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);
        end
    elseif self.openType == "awake_dungeon" then
        -- 觉醒试炼
        carvingNode:setVisible(true);

        local carvingBg = findChildByName(self.node, "CT/carving/carving_bg");
        local carvingImage = findChildByName(self.node, "CT/carving/icon");

        carvingImage:loadTexture(getAwakeIconPath("awake_dungeon"));
        setGrayTransMode(carvingImage, true);

        -- 显示功能描述
        local textLabel = ccui.Text:create();
        textLabel:setPositionY(propDescNode:getPositionY() - 68);
        TextStyleM.setTextStyle(textLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        textLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);

        local desc = getLocStr("upgrade_awake_dungeon_desc");
        if not AwakeM.isAwakeOpened(self.classId) then
            desc = desc .. string.format(getLocStr("upgrade_awake_no_open"), PetM.query(self.classId, "short_name"));
        end
        textLabel = applyString(textLabel, desc);
        propDescNode:addChild(textLabel);

        -- "前往神庙试炼"
        btnOk:setTitleText(getLocStr("go_awake_dungeon"));

        if AwakeM.isAwakeOpened(self.classId) and
            AwakeM.canAwakeDungeonTrial(self.classId) == true then
            btnOk:setBright(true);
            btnOk:setTouchEnabled(true);
        else
            btnOk:setBright(false);
            btnOk:setTouchEnabled(false);
        end
    elseif self.openType == "awake_carving" then
        -- 建造雕像
        carvingNode:setVisible(true);

        local carvingBg = findChildByName(self.node, "CT/carving/carving_bg");
        local carvingImage = findChildByName(self.node, "CT/carving/icon");

        carvingImage:loadTexture(getAwakeIconPath("carving"));
        setGrayTransMode(carvingImage, true);

        -- 属性描述
        local propDesc = AwakeM.fetchAwakeCarvingPropsDesc(self.classId);
        local propStr = propDesc[1] .. "\n" .. propDesc[2];
        local strList = string.explode(propStr, "\n");

        for index, str in ipairs(strList) do
            local textLabel = ccui.Text:create();
            textLabel:setPositionY(propDescNode:getPositionY() - 34 * index);
            TextStyleM.setTextStyle(textLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
            textLabel:getVirtualRenderer():setHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER);
            textLabel:setString(str);

            propDescNode:addChild(textLabel);
        end

        -- "建造英雄雕像"
        btnOk:setTitleText(getLocStr("go_awake_carving"));

        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    end

    -- 绘制背景宠物
    local petIcon = findChildByName(self.node, "CT/pet_icon");
    petIcon:loadTexture(getHeroLargeIconPath(self.classId));
    petIcon:setOpacity(75);
    petIcon:setScale(1.3);
end

function UIHeroUpgradeRank:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIHeroUpgradeRank:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIHeroUpgradeRank 界面析构清理");
            EventMgr.removeAll("UIHeroUpgradeRank");
        end
    end);

    -- 注册英雄升阶的回调
    EventMgr.register("UIHeroUpgradeRank", event.UPGRADE_PET_RANK, function(args)
        self:redraw();
    end);

    -- 注册英雄穿上装备的回调
    EventMgr.register("UIHeroUpgradeRank", event.EQUIP, function(args)
        self:whenEquip();
    end);
end

function UIHeroUpgradeRank:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIHeroUpgradeRank");
        end
    end

    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册提升阶位按钮点击事件
    local btnRank = findChildByName(self.CT, "btn_ok");
    local function onRankClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if self.openType == "awake_dungeon" then
                -- 觉醒试炼
                if AwakeM.isAwakeOpened(self.classId) and
                    AwakeM.canAwakeDungeonTrial(self.classId) == true then
                    -- 打开觉醒试炼地牢界面
                    require "game/ui/form/dungeon/UIEnterDungeon"

                    -- 进入地牢
                    if UIMgr:getCurrentScene():isOpen("UIEnterDungeon") then
                        UIMgr:getCurrentScene():removeForm("UIEnterDungeon");
                    end
                    local dungeonId = AwakeM.query(self.classId, "dungeon");
                    local uiEnterDungeon = UIEnterDungeon.create(dungeonId);
                    UIMgr.getCurrentScene():addForm(uiEnterDungeon);
                    AudioM.playFx("ui_open1");
                end
            elseif self.openType == "awake_carving" then
                -- 冈布奥雕像
                if AwakeM.getCarvingState() == AwakeM.CARVING_STATE_UPGRADING then
                    local finishTime = AwakeM.getCarvingFinishTime();
                    local serverTime = TimeM.getServerTime();
                    local leftTime = finishTime - serverTime;
                    if leftTime < 0 then
                        leftTime = 0;
                    end

                    local hours = math.floor(leftTime / 3600);
                    local mins =  math.floor((leftTime % 3600) / 60);
                    local secs =  (leftTime % 3600) % 60;

                    local desc = string.format(getLocStr("waite_for_carving"), hours, mins, secs);

                    local msgList = {desc,};
                    local UIHeroSpeak = UIHeroSpeak.create(self, AwakeM.getCarvingHeroId(), msgList, "B_FLY_IN", "B_FLY_OUT");
                    UIMgr.getCurrentScene():addForm(UIHeroSpeak);
                    return;
                elseif AwakeM.getCarvingState() == AwakeM.CARVING_STATE_FINISH then
                    local desc = getLocStr("waite_for_carving2");

                    local msgList = {desc,};
                    local UIHeroSpeak = UIHeroSpeak.create(self, AwakeM.getCarvingHeroId(), msgList, "B_FLY_IN", "B_FLY_OUT");
                    UIMgr.getCurrentScene():addForm(UIHeroSpeak);
                    return;
                end

                local ret = AwakeM.canCarving(self.classId);

                if ret == true then
                    -- 打开雕像界面
                    if UIMgr:getCurrentScene():isOpen("UIAwakeCarvingMain") then
                        UIMgr:getCurrentScene():removeForm("UIAwakeCarvingMain");
                    end
                    require "game/ui/form/awake/UIAwakeCarvingMain"
                    local uiForm = UIAwakeCarvingMain.create(self.classId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                    AudioM.playFx("ui_open1");
                else
                    alert(getLocStr(ret));
                end
            else
                -- 冈布奥进阶
                if TrainingM.getState() == TrainingM.TRAINING_STATE_UPGRADING then
                    -- 当前剩余时间
                    local finishTime = TrainingM.getFinishTime();
                    local serverTime = TimeM.getServerTime();
                    local leftTime = finishTime - serverTime;
                    if leftTime < 0 then
                        leftTime = 0;
                    end

                    local hours = math.floor(leftTime / 3600);
                    local mins =  math.floor((leftTime % 3600) / 60);
                    local secs =  (leftTime % 3600) % 60;

                    local desc = string.format(getLocStr("waite_for_training"), hours, mins, secs);

                    local msgList = {desc,};
                    local UIHeroSpeak = UIHeroSpeak.create(self, TrainingM.getHeroId(), msgList, "B_FLY_IN", "B_FLY_OUT");
                    UIMgr.getCurrentScene():addForm(UIHeroSpeak);
                elseif TrainingM.getState() == TrainingM.TRAINING_STATE_FINISH then
                    local desc = getLocStr("waite_for_training2");

                    local msgList = {desc,};
                    local UIHeroSpeak = UIHeroSpeak.create(self, TrainingM.getHeroId(), msgList, "B_FLY_IN", "B_FLY_OUT");
                    UIMgr.getCurrentScene():addForm(UIHeroSpeak);
                elseif PetM.isActivePet(self.classId) then
                    -- 出战中
                    alert(getLocStr("your_pet_is_active"));
                else
                    -- 选择英雄
                    Operation.cmd_pet_prepare_training(self.classId);
                    -- 打开训练室界面
                    --local UITrainingMain = UITrainingMain.create(self.classId);
                    --UIMgr.getCurrentScene():addForm(UITrainingMain);
                    -- 已选定，打开升阶确认界面
                    local uiForm = UITrainingHeroUpgrade.create(self.classId);
                    UIMgr.getCurrentScene():addForm(uiForm);
                    AudioM.playFx("ui_open1");
                end
            end
        end
    end

    btnRank:addTouchEventListener(onRankClick);

    -- 注册武器按钮点击事件
    --[[local weaponImage = findChildByName(self.node, "CT/weapon/weapon_bg");
    local function OnWeaponCompoundClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("equip_put");
            if sender.classId then
                -- 显示武器/徽章详情界面
                if UIMgr.getCurrentScene():isOpen("UIWeaponsExplain") then
                    UIMgr.getCurrentScene():removeFormByName("UIWeaponsExplain");
                end

                local uiUIWeaponsExplain = UIWeaponsExplain.create(sender.classId);
                UIMgr.getCurrentScene():addForm(uiUIWeaponsExplain);

            else
                local pet = self.pet;

                -- 如果获取不到升阶所需的武器或者所需武器的阶位为1，则不显示合成界面
                local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_WEAPON);
                if self:equipWeapons(pet, ret[1], EQUIP_TYPE_WEAPON) then
                    return;
                end

                -- 显示合成界面
                UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
                local UIItemCompound = UIItemCompound.create(self.classId, ret[1]);
                UIMgr.getCurrentScene():addForm(UIItemCompound);
            end
        end
    end
    weaponImage:addTouchEventListener(OnWeaponCompoundClick)

    -- 注册徽章合成按钮点击事件
    local medalImage  = findChildByName(self.node, "CT/medal/medal_bg");
    local function onMedalClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if sender.classId then
                -- 显示武器/徽章详情界面
                if UIMgr.getCurrentScene():isOpen("UIWeaponsExplain") then
                    UIMgr.getCurrentScene():removeFormByName("UIWeaponsExplain");
                end

                local uiUIWeaponsExplain = UIWeaponsExplain.create(sender.classId);
                UIMgr.getCurrentScene():addForm(uiUIWeaponsExplain);
            else
                local pet = self.pet;

                local ret = PetM.getUpgradeRankEquip(pet, EQUIP_TYPE_MEDAL);
                if self:equipWeapons(pet, ret[1], EQUIP_TYPE_MEDAL) then
                    return;
                end

                -- 显示合成界面
                UIMgr.getCurrentScene():removeFormByName("UIItemCompound");
                local UIItemCompound = UIItemCompound.create(self.classId, ret[1]);
                UIMgr.getCurrentScene():addForm(UIItemCompound);
            end
        end
    end
    medalImage:addTouchEventListener(onMedalClick);]]
end

-- 装备武器
function UIHeroUpgradeRank:equipWeapons(pet, classId, type)
    local count = ItemM.getAmount(ME.user,classId);
    if count <= 0 then
        return false;
    end

    local okFunc = function()
        -- 请求装备
        Operation.cmd_hero_equip(pet, classId);
    end

    local name = ItemM.query(classId, "name");
    local tipTxt = string.format(getLocStr("equip_weapons"), name);
    confirm(tipTxt, okFunc);

    return true;
end

function UIHeroUpgradeRank:canUpgradeRank(classId)
    local pet = PetM.getMyPet(classId);

    -- 根本没有该宠物
    if not pet then
        return false;
    end

    -- 获取宠物当前阶位
    local rank = pet:getRank();

    -- 该宠物已满阶
    if rank >= pet:query("max_rank") then
        return false;
    end

    -- 获取已经穿戴的武器
    local weaponClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_WEAPON, 1);
    local medalClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_MEDAL, 1);

    -- 判断
    local need = PetM.calcUpgradeRankNeed(classId, rank);
    for _, arr in pairs(need) do
        if arr[1] == 1 then
            local type = EquipM.query(arr[2], "type");
            local id = EquipM.getHeroEquip(pet, type, 1);
            if not id then
                -- 物品需求
                ok = ItemM.getAmount(ME.user, arr[2]) >= arr[3];
                local name = ItemM.query(arr[2], "name");

                -- 提示先穿戴上
                local tipTxt = string.format(getLocStr("please_equip_weapons"), name);
                self:showTip(tipTxt);
                return false;
            end
        else
            -- 属性消耗
            ok = ME.user.dbase:query(arr[2], 0) >= arr[3];
            if not ok then
                -- 属性不足
                local fieldName = FieldsM.getFieldName(arr[2]);
                local tipTxt = "";
                if fieldName == "money" then
                    tipTxt = string.format(getLocStr("hero_upgrade_rank_no_enough_money"));
                else
                    tipTxt = string.format(getLocStr("compose_enough_arrt"), fieldName);
                end

                self:showTip(tipTxt);
                return false;
            end
        end
    end

    local cost = PetM.calcUpgradeRankCost(classId, rank);
    if not cost then
        error(string.format("无法获取英雄升阶消耗(rank = %s)", tostring(rank)));
        return false;
    end

    local ok = true;

    for _, arr in pairs(cost) do
        if arr[1] == 1 then
            -- 物品消耗
            ok = ItemM.getAmount(ME.user, arr[2]) >= arr[3];
            local name = ItemM.query(arr[2], "name");

            -- 缺少物品
            local tipTxt = string.format(getLocStr("lack_equip_uprank"), name);
            self:showTip(tipTxt);
        else
            -- 属性消耗
            ok = ME.user.dbase:query(arr[2], 0) >= arr[3];
            if not ok then
                -- 属性不足
                local fieldName = FieldsM.getFieldName(arr[2]);
                local tipTxt = "";
                if fieldName == "money" then
                    tipTxt = string.format(getLocStr("hero_upgrade_rank_no_enough_money"));
                else
                    tipTxt = string.format(getLocStr("compose_enough_arrt"), fieldName);
                end

                self:showTip(tipTxt);
                return false;
            end
        end
    end

    return true;
end

-- 冈布奥穿装备
function UIHeroUpgradeRank:whenEquip()
    -- 播放特效
    local pet = self.pet;
    local weaponClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_WEAPON, 1);
    local medalClassId = EquipM.getHeroEquip(pet, EQUIP_TYPE_MEDAL, 1);
    local iconNode;
    local classId;
    if weaponClassId ~= self.lastWeaponClassId then
        iconNode = findChildByName(self.node, "CT/weapon/icon");
        classId = weaponClassId;
        -- 武器音效
        AudioM.playFx("admix_arms");
    elseif  medalClassId ~= self.lastMedalClassId then
        iconNode = findChildByName(self.node, "CT/medal/icon");
        classId = medalClassId;
        -- 勋章音效
        AudioM.playFx("admix_medal");
    end

    local function callFunc()
        -- 刷新界面
        self:redraw();
    end

    if iconNode and classId then
        playEquipWeaonAndMedalEffect(iconNode, classId, callFunc);
    end
end